import * as echarts from "echarts";
import Tool from "@/tool/Tool.js";

const defaultData = [
  {
    name: "测试1",
    val: 26,
  },
  {
    name: "测试2",
    val: 21,
  },
  {
    name: "测试3",
    val: 36,
  },
];

const domInterval = {};

let toolEcharts = {
  init(dom, option) {
    let myChart = echarts.init(dom);
    myChart.setOption(option);

    // 跟随屏幕自动变动
    // (window || {}).onresize = function() {
    // 	myChart.resize();
    // };

    function refresh() {
      myChart.setOption(option);
      myChart.resize({
        width: dom.clientWidth,
        height: dom.clientHeight,
      });
    }

    clearInterval(domInterval[dom.id]);
    // 1s 自动刷新
    domInterval[dom.id] = setInterval(refresh, 1000);
  },
  initRanking(dom, data = defaultData, title = {}) {
    let groups = Tool.groupBy(data, "groupName");

    toolEcharts.init(dom, {
      title,
      xAxis: {},
      yAxis: {
        data: data.map((item) => item.name),
        inverse: true,
        animationDuration: 300,
        animationDurationUpdate: 300,
      },
      series: Object.keys(groups).map((key) => ({
        realtimeSort: true,
        name: key,
        type: "bar",
        data: groups[key].map((item) => item.val),
        label: {
          show: true,
          position: "right",
          valueAnimation: true,
        },
      })),
      legend: {
        show: true,
      },
      animationDuration: 0,
      animationDurationUpdate: 3000,
      animationEasing: "linear",
      animationEasingUpdate: "linear",
    });
  },
};

export default toolEcharts;
